package model

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ OrderModel = (*customOrderModel)(nil)

type (
	// OrderModel is an interface to be customized, add more methods here,
	// and implement the added methods in customOrderModel.
	OrderModel interface {
		orderModel
		FindOneByOrderNum(ctx context.Context, orderNum string) (*Order, error)
	}

	customOrderModel struct {
		*defaultOrderModel
	}
)

// NewOrderModel returns a model for the database table.
func NewOrderModel(conn sqlx.SqlConn, c cache.CacheConf) OrderModel {
	return &customOrderModel{
		defaultOrderModel: newOrderModel(conn, c),
	}
}
func (m *defaultOrderModel) FindOneByOrderNum(ctx context.Context, orderNum string) (*Order, error) {
	publicOrderNumKey := fmt.Sprintf("%s%v", cachePublicOrderNumPrefix, orderNum)
	var resp Order
	err := m.QueryRowCtx(ctx, &resp, publicOrderNumKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
		query := fmt.Sprintf("select %s from %s where order_num = $1 limit 1", orderRows, m.table)
		return conn.QueryRowCtx(ctx, v, query, orderNum)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
